<template>
  <!--  日志-->
  <el-divider style="width: 100%"
    ><span style="font-size: 23px; font-family: '楷体'">日志</span></el-divider
  ><br />
  <!--  搜索表单-->
  <el-form :inline="true" :model="searchLog">
    <el-form-item label="用户名">
      <el-input
        style="width: 150px"
        v-model="searchLog.username"
        type="text"
        autocomplete="off"
        placeholder="输入搜索用户名"
        clearable
      />
    </el-form-item>
    <el-form-item label="日志类型">
      <el-select
        v-model="searchLog.logType"
        placeholder="选择日志类型"
        clearable
        style="width: 150px"
      >
        <el-option v-for="item in logTypeList" :label="item.value" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="日志时间">
      <el-date-picker
        v-model="date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 300px"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">搜索</el-button>
      <el-button type="info" @click="resetForm">清空</el-button>
    </el-form-item>
  </el-form>

  <el-row> <el-button type="danger" @click="sureDelete(null)">- &nbsp;批量删除</el-button> </el-row
  ><br />

  <!--  日志列表-->
  <el-table :data="logInfo" show-overflow-tooltip border @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" width="60" align="center" />
    <el-table-column property="username" label="操作人（管理员）" width="200" align="center" />
    <el-table-column property="logType" label="日志类型" width="200" align="center" />
    <el-table-column property="logOperate" label="日志内容" align="center" />
    <el-table-column property="logTime" label="操作时间" width="200" sortable align="center" />
    <el-table-column label="操作" width="200px" align="center">
      <template v-slot="{ row }">
        <el-button type="primary" @click="goDetail(row)">详情</el-button>
        <el-button type="danger" @click="sureDelete({ ...row }.logId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog
    v-model="dialogDetailVisible"
    align-center
    center
    title="日志详细信息"
    width="50%"
    style="height: 500px; background-color: #d1edc4"
  >
    <div class="info-box">
      <div class="item-box">
        <span class="label">操作人（管理员）：</span>
        <span class="des">{{ diaForm.username }}</span
        ><br />

        <span class="label">日志类型：</span>
        <span class="des">{{ diaForm.logType }}</span
        ><br />

        <span class="label">操作时间：</span>
        <span class="des">{{ diaForm.logTime }}</span
        ><br />

        <span class="label">日志内容：</span>
        <span class="des">{{ diaForm.logOperate }}</span
        ><br />
      </div>
    </div>
  </el-dialog>

  <!--  分页-->
  <div style="margin-top: 10px">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      background
      @size-change="SizeChange"
      @current-change="CurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { deleteLogByIds, getAllLog, getLogInfo } from '@/apis/log'

// 用于搜索和分页
const searchLog = ref({
  username: '',
  logType: '',
  logBeginTime: '',
  logEndTime: ''
})
const pageSize = ref(5)
const currentPage = ref(1)
const total = ref(30)
const dialogDetailVisible = ref(false)
const date = ref([])
const multipleSelection = ref([])
const selectIds = ref([])
const diaForm = ref({})

interface Log {
  logId: number
  username: string
  logType: string
  logOperate: string
  logTime: string
}

const logInfo = ref<Log[]>([
  {
    logId: 1,
    username: '测试日志1',
    logType: '156',
    logOperate: 'sfsfa',
    logTime: '2023-11-23 17:32:15'
  }
])

const log = ref<Log>({
  logId: 1,
  username: '',
  logOperate: '',
  logType: '',
  logTime: ''
})
const logTypeList = ref([{ value: '' }])
const page = () => {
  getLogInfo(
    searchLog.value.username,
    searchLog.value.logType,
    searchLog.value.logBeginTime,
    searchLog.value.logEndTime,
    pageSize.value,
    currentPage.value
  ).then((res) => {
    console.log('获取日志信息')
    if (res.data.code === 1) {
      console.log('获取成功')
      logInfo.value = res.data.data.rows
      total.value = res.data.data.total
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
      console.log('获取失败')
    }
  })
}

onMounted(() => {
  getAllLog().then((res) => {
    if (res.data.code === 1) {
      let type = ref(new Set())
      for (let i = 0; i < res.data.data.length; i++) {
        type.value.add(res.data.data[i].logType)
      }
      let i = 0
      for (let v of type.value.values()) {
        logTypeList.value[i] = { value: v }
        i++
      }
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
  page()
})
const handleSelectionChange = (val: number[]) => {
  multipleSelection.value = val
}
const submitForm = () => {
  currentPage.value = 1
  page()
}
const resetForm = () => {
  searchLog.value = {
    username: '',
    logType: '',
    logBeginTime: '',
    logEndTime: ''
  }
  date.value = []
  page()
}
const SizeChange = (val: number) => {
  pageSize.value = val
  page()
}
const CurrentChange = (val: number) => {
  currentPage.value = val
  page()
}
const goDetail = (row: any) => {
  diaForm.value = {}
  dialogDetailVisible.value = true
  diaForm.value = { ...row }
}
const sureDelete = (logId: number) => {
  ElMessageBox.confirm('确认删除日志吗?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (logId != null) {
        selectIds.value[0] = logId
      } else {
        for (let i = 0; i < multipleSelection.value.length; i++) {
          selectIds.value[i] = multipleSelection.value[i].logId
        }
      }
      if (selectIds.value === null || selectIds.value.length === 0) {
        ElMessage({ type: 'error', message: '未选择需删除的日志' })
        return false
      }
      deleteLogByIds(selectIds.value).then((res) => {
        if (res.data.code === 1) {
          ElMessage({ type: 'success', message: '删除成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消删除' })
    })
}

function Format(date) {
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  if (month < 10) month = '0' + month
  if (day < 10) day = '0' + day
  return year + '-' + month + '-' + day
}

watch(date, (newValue: Date[], oldValue: Date[]) => {
  if (newValue && newValue.length == 2) {
    searchLog.value.logBeginTime = Format(newValue[0])
    searchLog.value.logEndTime = Format(newValue[1])
  }
})
</script>
<style scoped>
.info-box {
  margin: -15px -10px 20px;
}
.info-box .item-box {
  height: 20px;
  line-height: 50px;
  font-size: 14px;
  font-weight: 400;
  color: #666666;
  text-align: left;
  margin-bottom: 14px;
}
.info-box .item-box .label {
  width: 50px;
  margin-left: 40px;
}
.info-box .item-box .des {
  color: #333333;
}
</style>
